package com.cssnj.portal.service.admin.positionrole;

import com.cssnj.portal.domain.admin.GlGwJsEntity;
import com.cssnj.portal.domain.admin.GlGwJsRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.predictech.framework.domain.common.JsonRequest;
import io.predictech.framework.domain.common.JsonResponse;
import io.predictech.framework.domain.exception.BaseException;
import io.predictech.framework.domain.exception.BaseSysException;
import io.predictech.framework.service.base.BaseService;
import io.predictech.framework.utility.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("positionroleService")
public class PositionroleService extends BaseService {

    @Autowired
    private GlGwJsRepository glGwJsRepository;

    //国税数据源
    @Qualifier("secondJdbcTemplate")
    @Autowired
    private JdbcTemplate secondJdbcTemplate;

    //地税数据源
    @Qualifier("thirdJdbcTemplate")
    @Autowired
    private JdbcTemplate thirdJdbcTemplate;

    @Override
    protected JsonResponse invokingService(JsonRequest jsonRequest) throws SQLException, BaseException {
        if ("init".equals(jsonRequest.getHandleCode())) {
            return init(jsonRequest);
        } else if ("queryGwLb".equals(jsonRequest.getHandleCode())) {
            return queryGwLb(jsonRequest);
        } else if ("queryJsByGwDm".equals(jsonRequest.getHandleCode())) {
            return queryJsByGwDm(jsonRequest);
        } else if ("saveGwJs".equals(jsonRequest.getHandleCode())) {
            return saveGwJs(jsonRequest);
        }
        return null;
    }

    //初始化
    private JsonResponse init(JsonRequest jsonRequest) throws SQLException {
        //默认以国税视角
        //查询国税岗位分类列表
        JsonResponse jsonResponse = new JsonResponse();
        List<Object> params = new ArrayList<Object>();
        params.add("Y");
        String sql = "SELECT DISTINCT A.GWFL_DM, A.GWFLMC FROM HX_QX.DM_QX_GWFL A, HX_DM_ZDY.DM_QX_GW B WHERE A.YXBZ = ? AND A.GWFL_DM = B.GWFL_DM ORDER BY A.GWFL_DM";
        List<Map<String, Object>> gwflList = this.queryDao.queryForList(secondJdbcTemplate, sql, params);
        jsonResponse.getRepData().put("gwflList", gwflList);
        //视角代码 1国税 2地税
        jsonResponse.getRepData().put("sjDm", "1");
        //视角列表
        List<Map<String, Object>> sjList = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sjDm", "1");
        map.put("sjMc", "原国税");
        sjList.add(map);
        map = new HashMap<String, Object>();
        map.put("sjDm", "2");
        map.put("sjMc", "原地税");
        sjList.add(map);
        jsonResponse.getRepData().put("sjList", sjList);
        return jsonResponse;
    }

    //根据条件查询岗位列表
    private JsonResponse queryGwLb(JsonRequest jsonRequest) throws SQLException, BaseException {
        String str_gwlist = "";
        SqlRowSet rs;
        JsonResponse jsonResponse = new JsonResponse();
        List<Map<String, Object>> gwList = null;
        String sql = "";
        String total_sql = "";
        Map<String, Object> map;
        Map<String, Object> gwmap;
        Map<String, Object> jsmap;
        List<Object> params = new ArrayList<Object>();
        List<Object> total_params = new ArrayList<Object>();
        //获取请求参数
        String sjlb = (String) jsonRequest.getReqData().get("sjlb");
        String gwfl = (String) jsonRequest.getReqData().get("gwfl");
        String jsnr = (String) jsonRequest.getReqData().get("jsnr");
        String rows = (String) jsonRequest.getReqData().get("rows");
        String page = (String) jsonRequest.getReqData().get("page");
        if (null == rows || "".equals(rows)) {
            rows = "10";
        }

        if (null == page || "".equals(page)) {
            page = "1";
        }
        sql = "SELECT HC, GWFLDM, GWFLMC, GWDM, GWMC, JSMS FROM (SELECT ROWNUM HC, GWFLDM, GWFLMC, GWDM, GWMC, JSMS FROM (SELECT B.GWFL_DM GWFLDM, B.GWFLMC, A.GW_DM GWDM, A.GWMC, '' AS JSMS FROM HX_DM_ZDY.DM_QX_GW A, HX_QX.DM_QX_GWFL B WHERE A.GWFL_DM = B.GWFL_DM AND (A.GWFL_DM = ? OR 1 = ?) AND (A.GWMC LIKE '%' || ? || '%' OR 1 = ?) AND A.YXBZ = 'Y' AND B.YXBZ = 'Y' ORDER BY B.GWFL_DM, A.GW_DM)) D WHERE HC >= ? * (? - 1) + 1 AND HC <= ? * ?";
        total_sql = "SELECT COUNT(1) AS GS FROM HX_DM_ZDY.DM_QX_GW A, HX_QX.DM_QX_GWFL B WHERE A.GWFL_DM = B.GWFL_DM AND (A.GWFL_DM = ? OR 1 = ?) AND (A.GWMC LIKE '%' || ? || '%' OR 1 = ?) AND A.YXBZ = 'Y' AND B.YXBZ = 'Y'";
        //岗位分类
        if ("".equals(gwfl)) {
            params.add("0");
            params.add("1");
            total_params.add("0");
            total_params.add("1");
        } else {
            params.add(gwfl);
            params.add("0");
            total_params.add(gwfl);
            total_params.add("0");
        }
        //检索内容
        if (null == jsnr || "".equals(jsnr)) {
            params.add("0");
            params.add("1");
            total_params.add("0");
            total_params.add("1");
        } else {
            params.add(jsnr);
            params.add("0");
            total_params.add(jsnr);
            total_params.add("0");
        }
        params.add(rows);
        params.add(page);
        params.add(rows);
        params.add(page);
        if ("1".equals(sjlb)) {
            //国税
            gwList = this.queryDao.queryForList(secondJdbcTemplate, sql, params);
            map = this.queryDao.queryForMap(secondJdbcTemplate, total_sql, total_params);
        } else {
            //地税
            gwList = this.queryDao.queryForList(thirdJdbcTemplate, sql, params);
            map = this.queryDao.queryForMap(thirdJdbcTemplate, total_sql, total_params);
        }
        String total = String.valueOf(map.get("gs"));
        if (gwList.isEmpty()) {
            gwList = new ArrayList<Map<String, Object>>();
        } else {
            //有岗位则先查询所有的角色列表，在循环增加
            List<String> ls_gw_list = new ArrayList<>();
            Map<String, Object> js_params = new HashMap<String, Object>();
            for (int i = 0; i < gwList.size(); i++) {
                ls_gw_list.add((String) gwList.get(i).get("GWDM"));
            }
            js_params.put("GW_ID", ls_gw_list);
            List<Map<String, Object>> jsList = this.queryDao.queryForList("SELECT C.GW_ID GWID, WM_CONCAT(D.JS_MC) JSMS FROM GL_GW_JS C, GL_JS D WHERE C.GW_ID IN (:GW_ID) AND C.JS_ID = D.JS_ID GROUP BY C.GW_ID", js_params);
            //循环岗位
            for (int i = 0; i < gwList.size(); i++) {
                gwmap = gwList.get(i);
                //循环岗位角色
                for (int j = 0; j < jsList.size(); j++) {
                    jsmap = jsList.get(j);
                    if (gwmap.get("GWDM").equals(jsmap.get("GWID"))) {
                        gwmap.put("JSMS", jsmap.get("JSMS"));
                        break;
                    }
                }
            }
        }
        try {
            ObjectMapper objectMapper = StringUtil.getBaseObjectMapper();
            HashMap<String, Object> r_map = new HashMap<String, Object>();
            r_map.put("total", total);
            r_map.put("rows", gwList);
            jsonResponse.getRepData().put("str", objectMapper.writeValueAsString(r_map));
        } catch (JsonProcessingException e) {
            throw new BaseSysException(e.getMessage());
        }
        return jsonResponse;
    }

    //根据岗位代码查询角色列表
    private JsonResponse queryJsByGwDm(JsonRequest jsonRequest) throws SQLException, BaseSysException {
        JsonResponse jsonResponse = new JsonResponse();
        //获取请求参数
        String gwdm = (String) jsonRequest.getReqData().get("gwdm");
        List<Object> params = new ArrayList<Object>();
        params.add(gwdm);
        String sql = "select a.js_id id, a.js_mc text, 'open' state, (select case when count(1) > 0 then 'true' else 'false' end from gl_gw_js b where b.gw_id = ? and b.js_id = a.js_id) checked from gl_js a where a.ztbj_dm = '1'";
        List<Map<String, Object>> jsList = new ArrayList<Map<String, Object>>();
        Map<String, Object> map;
        SqlRowSet rs = this.queryDao.queryForRowSet(sql, params);
        while (rs.next()) {
            map = new HashMap<String, Object>();
            map.put("id", rs.getString("id"));
            map.put("text", rs.getString("text"));
            map.put("state", rs.getString("state"));
            if ("true".equals(rs.getString("checked"))) {
                map.put("checked", true);
            } else {
                map.put("checked", false);
            }
            jsList.add(map);
        }
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        map = new HashMap<String, Object>();
        map.put("id", "");
        map.put("text", "全部");
        map.put("state", "open");
        map.put("flag", false);
        map.put("children", jsList);
        list.add(map);
        jsonResponse.getRepData().put("jsList", list);
        return jsonResponse;
    }

    //保存岗位角色
    @Transactional
    public JsonResponse saveGwJs(JsonRequest jsonRequest) throws SQLException, BaseSysException {
        JsonResponse jsonResponse = new JsonResponse();
        //获取请求参数
        String gwdm = (String) jsonRequest.getReqData().get("gwdm");
        String nodes = (String) jsonRequest.getReqData().get("nodes");
        //获取当前人员
        String swrydm = (String) jsonRequest.getReqData().get("swrydm");
        //获取当前时间
        Timestamp lrsj = this.queryDao.getSystimestamp();
        GlGwJsEntity vo;
        //删除当前岗位下的角色
        glGwJsRepository.deleteByGwdm(gwdm);
        //有角色就保存
        if (!"".equals(nodes)) {
            String[] jsArr = nodes.split(",");
            for (int i = 0; i < jsArr.length; i++) {
                vo = new GlGwJsEntity();
                vo.setGwId(gwdm);
                vo.setJsId(jsArr[i]);
                vo.setLrryId(swrydm);
                vo.setLrSj(lrsj);
                vo.setXyBj("1");
                glGwJsRepository.save(vo);
            }
        }
        return jsonResponse;
    }

}
